<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/12/27
 * Time: 11:32
 */

namespace app\admin\controller;

use think\Db;

class Company extends Main
{
    public $company_id;

    public function _initialize()
    {
        parent::_initialize();
        $this->company_id = isession('company_id');
    }

    /**
     * 公司管理
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function list()
    {
        if (isession('type') == 2) {//子公司
            $info = DB::name("company")->where('id', $this->company_id)->find();
            isset($info['use_capacity']) && $info['use_capacity'] = diskTransform($info['use_capacity']);
            $this->assign('data', $info);
            $this->assign('type', isession('type'));
            $this->assign('zindex', 1);
            return $this->fetch('info');
        }
        //获取子公司id
        $where['flag'] = 1;
        $where['type'] = 2;
        $company_ids = Db::name('user')
            ->distinct(true)
            ->field('company_id')
            ->where($where)
            ->select();
        $data = [];
        $list = [];
        if (checkArr($company_ids)) {
            $company_id = array_column($company_ids, 'company_id');
            $cwhere['id'] = ['in', $company_id];
            sget('name') && $cwhere['name'] = ['like', '%' . sget('name') . '%'];
            $data = DB::name("company")
                ->where($cwhere)
                ->paginate(15, false, ['query' =>
                    [
                        'name' => sget('name')
                    ]]);
            $list = $data->all();
            if (checkArr($list)) {
                foreach ($list as $key => $value) {
                    $list[$key]['bar'] = 0;
                    if ($value['use_capacity'] > 0) {
                        $list[$key]['use_capacity'] = diskTransform($value['use_capacity']);
                        $list[$key]['bar'] = getDiskBar($value['upload_capacity'], $value['use_capacity']);
                    }
                }
            }
        }
        $this->assign('data', $data);
        $this->assign('list', $list);
        return $this->fetch('list');
    }

    /**
     * 公司详情
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function info($id)
    {
        if (post()) {
            $data = post();
            $this->changeCompany($data);
            unset($data['id']);
            DB::name("company")->where('id', post('id'))->update($data);
            $this->success("提交成功");
        } else {
            $info = DB::name("company")->where('id', $id)->find();
            isset($info['use_capacity']) && $info['use_capacity'] = diskTransform($info['use_capacity']);
            $this->assign('data', $info);
            $this->assign('zindex', 2);
            $this->assign('type', isession('type'));
            return $this->fetch('info');
        }
    }

    /**
     * 公司信息提交更改状态
     * @param array $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function changeCompany($data = [])
    {
        $info = DB::name("company")->where('id', $data['id'])->find();
        if ($data['status'] == $info['status']) {
            return true;
        }
        //禁用公司，禁止公司名下所有用户,删除公司下面所有角色权限信息
        if ($data['status'] == 2) {
            DB::name('user')->where('company_id', $data['id'])->update(['status' => 2]);
            //查找管理员之外的角色
            $role = DB::name('auth_group')->field('id')->where(['company_id' => $data['id'], 'concierge' => 2])->select();
            if (checkArr($role)) {
                $role_id = array_column($role, 'id');
                //删除角色权限
                DB::name('auth_role_power')->where(['role_id' => ['in', $role_id]])->delete();
            }
            //禁用用户登录日志增加一条新记录
            $user = DB::name('user')->field('id,username')->where('company_id', $data['id'])->select();
            if (checkArr($user)) {
                $time = time();
                foreach ($user as $value) {
                    $insertData[] = array(
                        'uid' => $value['id'],
                        'uname' => $value['username'],
                        'login_time' => $time,
                        'login_ip' => '#127.0.0.1'
                    );
                }
                DB::name('user_log')->insertAll($insertData);
            }
        } elseif ($data['status'] == 1) {
            //启用公司，启用公司名下管理员账号
            DB::name('user')->where(['company_id' => $data['id'], 'super' => 3])->update(['status' => 1]);
        }
        return true;
    }


    /**
     * 公司支付信息列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function payment()
    {
        if (checkEntranceList()) {//总公司管理员，跳转选子公司页面
            action('admin/globalFun/choose', ['backtrack' => "payment"]);
            return $this->fetch(APP_PATH . request()->module() . '/view/public/choose.html');
        }

        $company_id = iget('company_id') ? iget('company_id') : $this->company_id;
        $data = Db::name('pay_account')
            ->where(['company_id' => $company_id])
            ->order('id desc')
            ->paginate(12, false, ['query' =>
                [
                    'company_id' => $company_id
                ]]);
        $this->assign('payment', $data);
        return $this->fetch('payment');
    }

    /**
     * 添加支付信息
     * @return mixed
     */
    public function paymentAdd()
    {
        if (post()) {
            $data = post();
            $data['company_id'] = $this->company_id;
            $data['timestamp'] = time();
            DB::name("pay_account")->insert($data);
            $this->success("添加成功");
        } else {
            if (checkEntranceAdd()) {
                $this->error("当前状态不允许添加信息");
            }
            return $this->fetch('paymentAdd');
        }
    }

    /**
     * 编辑支付信息
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function paymentEdit($id)
    {
        if (post()) {
            $data = post();
            if (checkSubmitEdit()) {
                $this->error("当前状态不允许编辑信息");
            }
            unset($data['id']);
            unset($data['company_id']);
            DB::name("pay_account")->where('id', post('id'))->update($data);
            $this->success("更新成功");
        } else {
            $data = DB::name("pay_account")->where('id', $id)->find();
            $this->assign('payment', $data);
            return $this->fetch('paymentEdit');
        }
    }

    /**
     * 删除支付信息
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function paymentDel()
    {
        $data = post();
        if (checkArr($data['id'])) {
            $where['id'] = ['in', $data['id']];
            $where1['account_id'] = ['in', $data['id']];
        } else {
            $where['id'] = $data['id'];
            $where1['account_id'] = $data['id'];
        }
        Db::name('pay_account')->where($where)->delete();
        Db::name('user_account')->where($where1)->delete();

        $this->success("删除成功");
    }

    /**
     * 支付信息分配用户
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function paymentUser($id)
    {
        if (post()) {
            $data = post();
            if (!isset($data['users']) || count($data['users']) == 0) {
                //删除该支付信息绑定用户
                Db::name('user_account')->where('account_id', $data['id'])->delete();
                $this->success('分配成功');
            }
            //删除该支付信息绑定用户
            Db::name('user_account')->where('account_id', $data['id'])->delete();
            foreach ($data['users'] as $key => $value) {
                $insertData[] = ['user_id' => $value, 'account_id' => $data['id']];
            }
            Db::name('user_account')->insertAll($insertData);
            $this->success('分配成功');
        } else {
            $company_id = iget('company_id') ? iget('company_id') : $this->company_id;
            $user = $this->getAllUser($company_id);
            //用户所有不重复角色id
            $role = [];
            if (checkArr($user)) {
                $role_id = join(',', array_unique(array_column($user, 'role_id')));
                $role = arrayCombine($this->getRoleById($role_id), 'id');
                foreach ($user as $key => $value) {
                    isset($role[$value['role_id']]) && $role[$value['role_id']]['user'][] = $value;
                }
            }
            //获取当前支付信息绑定的用户
            $account = Db::name('user_account')
                ->where('account_id', $id)
                ->select();
            $this->assign('user', arrayCombine($account, 'user_id'));
            $this->assign('role', $role);
            return $this->fetch('paymentUser');
        }
    }

}